package com.chap1;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <p>
 * <code>UseFuture</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-20 14:10
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class UseFuture {
    private static class UseCallable implements Callable<Integer>{
        private int sum;

        @Override
        public Integer call() throws Exception {
            System.out.println("callable子线程开始计算！");
            for (int i = 0; i < 5000; i++) {
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("callable子线程计算任务中断！");
                    return null;
                }
                sum+=i;
                System.out.println("sum="+sum);
            }
            System.out.println("callable子线程计算结束！结果为："+sum);
            return sum;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        UseCallable useCallable = new UseCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(useCallable);
        Random r = new Random();
        new Thread(futureTask).start();

        Thread.sleep(1);
        int i = r.nextInt(100);
        System.out.println("==========================================================随机数i="+i);
        if (i>50){
            System.out.println("Get usecallable result = "+futureTask.get());
        }else {
            System.out.println("cancel .....");
            futureTask.cancel(true);
        }
    }
}
